package com.linkage.jz.bankruptcy.fragment.Project;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.OtherUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.SelZQUserListActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserZQShowDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUserListActivity;
import com.linkage.jz.bankruptcy.adapter.ProManagerListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.ProZQUserConfirmListViewAdapter;
import com.linkage.jz.bankruptcy.bean.ManagerUserInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailAuthBaseInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserInfo;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateUserDialog;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.chat.ChatDetailActivity;
import com.linkage.seapeak.activity.vote.CreditorMultiSelectActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.linkage.seapeak.view.CreditorOrderDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;
import static com.linkage.jz.bankruptcy.R2.id.rv_recyclerview_data;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class ZQUserConfirmListFrgment extends BaseFragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView text, tv_total, order_item;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private ProZQUserConfirmListViewAdapter mAdapter;
    private ArrayList<ZQUserInfo> mData;
    private RecyclerView mDataRv;
    private TextView tv_searchtxt;
    private String mProID;
    private ShapeLoadingDialog shapeLoadingDialog ;
    private RelativeLayout rl_search;
    private LinearLayout ll_nodata;
    private RelativeLayout ll_total;
    private String orderBy = "desc";
    private String orderColumn;
    private ZQUserDetailAuthBaseInfo mAuthBaseInfo;
    private CreateUserDialog createUserDialog;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private String managerFlag;

    private String groupid;
    private String isOpen;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zquserconfirm_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
        Bundle bundle =this.getArguments();//得到从Activity传来的数据

        if(bundle!=null){
            mProID = bundle.getString("proid");
            managerFlag = bundle.getString("managerFlag");
            isOpen = bundle.getString("openAuth");
        }
        orderColumn = "";

//        getData();


    }

    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");
        ll_nodata = (LinearLayout)view.findViewById(R.id.ll_nodata);
    }

    private void initRecyclerView(final View view) {

        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
//        mDataRv.addItemDecoration(new Divider(getActivity()));
        tv_searchtxt = (TextView) view.findViewById(R.id.tv_searchtxt);
        ll_total = (RelativeLayout) view.findViewById(R.id.ll_total);
        tv_total = (TextView)view.findViewById(R.id.tv_total);
        order_item = (TextView) view.findViewById(R.id.order_item);
        rl_search = (RelativeLayout) view.findViewById(R.id.rl_search);

        order_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final CreditorOrderDialog dialog = new CreditorOrderDialog(getActivity());
                dialog.init(getActivity(), orderColumn, orderBy);
                dialog.setSureListener(new CreditorOrderDialog.OnSureListener() {
                    @Override
                    public void onSure(int orderType, int orderOrien) {
//                        declareTime 申报时间
//                        confirmTime 确认时间
//                        amountDeclared 申报金额
//                        confirmAmount 确认金额
                        if (orderType == 1)
                            orderColumn = "confirmAmount";
                        else if (orderType == 2)
                            orderColumn = "amountDeclared";
                        else if (orderType == 3)
                            orderColumn = "confirmTime";
                        else if (orderType == 4)
                            orderColumn = "declareTime";
                        orderBy = orderOrien == 2 ? "asc" : "desc";
                        getData();
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

        tv_searchtxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SelZQUserListActivity.start(getActivity(),mProID,isOpen);
            }
        });

//        tv_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener(){
//            @Override
//
//            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
//
//// TODO Auto-generated method stub
//
//                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
//
//                {
//                    InputMethodManager imm = (InputMethodManager) view.getContext()
//                            .getSystemService(Context.INPUT_METHOD_SERVICE);
//                    if (imm != null) {
//                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
//                    }
//                    mData.clear();
//                                mAdapter.notifyDataSetChanged();
//
//                    getData();
////                    Toast.makeText(AddMemberActivity.this,"呵呵",Toast.LENGTH_SHORT).show();
//
//// search pressed and perform your functionality.
//
//                }
//
//                return false;
//
//            }
//
//        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new ProZQUserConfirmListViewAdapter(mDataRv,getActivity());
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<ZQUserInfo>();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    PublicNoticeDialog noticeDialog;
    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        ZQUserInfo infoTmp = mAdapter.getItem(position);
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
//            mAdapter.removeItem(position);
        }

        if(childView.getId() == R.id.iv_manageuser_add)
        {
//            ZQUserInfo infoTmp = mData.get(position);
//            groupid = infoTmp.getGroup().getId();
//            createUserDialog = new CreateUserDialog(getActivity(),onClickListener);
//            createUserDialog.show();
        }

        if (childView.getId() == R.id.iv_email) {
            if(mAuthBaseInfo!=null )
            {
//                mAuthBaseInfo
                if(!mAuthBaseInfo.isContactCreditor())
                {
                    ToastUtil.showShort("您没有权限操作");
                    return;
                }
            }
            if (infoTmp.getId() != null)
                ChatDetailActivity.start(getActivity(), infoTmp.getId(),
                        infoTmp.getCreditorName(), infoTmp.getBankruptcyProjectId());
        }

        if (childView.getId() == R.id.iv_phone) {

//            if(mAuthBaseInfo!=null )
//            {
////                mAuthBaseInfo
//                if(!mAuthBaseInfo.isContactCreditor())
//                {
//                    ToastUtil.showShort("您没有权限操作");
//                    return;
//                }
//            }
            if (infoTmp != null || !TextUtils.isEmpty(infoTmp.getContact())) {

                final String phone = infoTmp.getContact();
                SetPhone(phone);
                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.ll_close:
                                noticeDialog.dismiss();
                                break;
                            case R.id.btn_chancel_notice:

                                if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_SMS_PERMISSION)){

                                    try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                        Intent intent = new Intent(Intent.ACTION_SENDTO);
                                        Uri data = Uri.parse("smsto:" + phone);
                                        intent.setData(data);
                                        startActivity(intent);

//                                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
//                                                intent.putExtra("sms_body", message);
//                                                startActivity(intent);

                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                                noticeDialog.dismiss();
                                break;

                            case R.id.btn_save_notice:
                                if(!"".equalsIgnoreCase(phone)) {
                                    if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                                        try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                            Intent intent = new Intent(Intent.ACTION_CALL);
                                            Uri data = Uri.parse("tel:" + phone);
                                            intent.setData(data);
                                            startActivity(intent);
                                        }catch (Exception ex){
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                                noticeDialog.dismiss();

                                break;
                        }
                    }
                }, 2,phone, phone,"发短信","拨打电话");
                noticeDialog.show();
            } else
                showToast("无法获取号码");
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {

            return true;
        }
        if(childView.getId() == R.id.tv_item_bgaswipe_edit) {

            return true;
        }


        return false;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_u:
                    createUserDialog.dismiss();
                    break;
                case R.id.btn_save_u:
                    String name = createUserDialog.text_name_u.getText().toString().trim();
                    String phone = createUserDialog.text_mobile_u.getText().toString().trim();
                    addUser(groupid,name,phone);
                    break;

            }
        }
    };


    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        ZQUserInfo model = mAdapter.getItem(position);
        if(model !=null) {

            if("true".equalsIgnoreCase(managerFlag)) {
                if("true".equalsIgnoreCase(isOpen)) {
                    Intent intent = new Intent(getActivity(), ZQUserDetailActivity.class);
                    intent.putExtra("creditorId", model.getId());
                    intent.putExtra("proid", mProID);
                    getActivity().startActivity(intent);
                }
            }else{
//                Intent intent = new Intent(getActivity(), ZQUserZQShowDetailActivity.class);
//                intent.putExtra("creditorId", model.getId());
//                intent.putExtra("proid", mProID);
//                int
                if("true".equalsIgnoreCase(isOpen)) {
                    ZQUserZQShowDetailActivity.start(getActivity(), model);
                }
//                getActivity().startActivity(intent);

            }
//            if(model.getCurType()==1)
//            {
//                Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);
//                intent.putExtra("info",new Gson().toJson(model));
//                 getActivity().startActivity(intent);
//            }


        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }
    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

//        final String title = tv_searchtxt.getText().toString();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mProID)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("creditorName","")
                .add("process","5")
                .add("pageNo","1")
                .add("pageSize","100")
                .add("orderBy", orderBy)
                .add("orderColumn", orderColumn)
                .build();

        String url = Consts.WEBURL_CONFIRMEDLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                runOnUiThread(new Runnable(){
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        Toast.makeText(PersonSettingOrgActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
//
//                    }
//
//                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{

//                    LawListInfo model = new LawListInfo();
////                                model.setId(data.getString("id"));
//                    model.setTitle("title");
//                    model.setContent("fileName");
//                    mData.add(model);
//                    getActivity().runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            mAdapter.notifyDataSetChanged();
//
//                        }
//
//                    });

                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobj = object.getJSONObject("data");
                        JSONObject dataobj5 = dataobj.getJSONObject("5");

                        mAuthBaseInfo= new Gson().fromJson(object.getJSONObject("data").getJSONObject("auth").toString(), ZQUserDetailAuthBaseInfo.class);

//                        JSONObject groupListobj = dataobj5.getJSONObject("list");
//                        Iterator<String> it = groupListobj.keys();
                        List<ZQUserInfo> list = new ArrayList<>();
//                        while(it.hasNext()){
//                            String key = it.next();
//                            Gson gson = new Gson();
                            ZQUserInfo[] array = new Gson().fromJson(dataobj5.optString("list"),ZQUserInfo[].class);

//                            ManagerUserInfo managerUserInfo = new ManagerUserInfo();


                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                if((array== null || array.length == 0) )
                                {

                                    ll_nodata.setVisibility(View.VISIBLE);
                                    mDataRv.setVisibility(View.GONE);
                                    rl_search.setVisibility(View.GONE);
                                    ll_total.setVisibility(View.GONE);

                                }else{
//                                    ((ZQUserListActivity)getActivity()).menuShow(true);
                                    mData.clear();
                                    mAdapter.notifyDataSetChanged();
                                    mDataRv.setVisibility(View.VISIBLE);
                                    ll_nodata.setVisibility(View.GONE);
                                    rl_search.setVisibility(View.VISIBLE);
                                    ll_total.setVisibility(View.VISIBLE);
                                    tv_total.setText("共计:"+array.length+"人");
                                    int arynum = 0;
                                    for(int i=0;i<array.length;i++)
                                    {
                                        ZQUserInfo infoTmp = array[i];
                                        list.add(infoTmp);

                                    }
//                        }

                                    mData.addAll(list);

                                    mAdapter.setAuth(mAuthBaseInfo);
                                    mAdapter.notifyDataSetChanged();
                                }


                            }

                        });




//                        mAdapter.notifyDataSetChanged();

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                        }
//
//                    });
                }
            }
        });
    }


    public void addGroup(String groupname)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId",mProID)
                .add("groupName", groupname)
                .build();

        String url = Consts.WEBURL_ADDGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void addUser(String groupId,String name,String phone)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId", mProID)
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                                if(createUserDialog != null)
                                {
                                    createUserDialog.dismiss();
                                }
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                if("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg")))
                                {
                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
                                }
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
